package chen.jia.xin.finalproject;

import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

//下载任务(使用Async异步机制)
public class DownloadTask extends AsyncTask<String,Integer,Integer>{
    //构造函数传入接口
    public DownloadTask(DownloadListener downloadListener) {
        this.downloadListener = downloadListener;
    }

    //下载任务的结果
    public final static int TYPE_SUCCESS = 0;
    public final static int TYPE_FAILED = 1;
    public final static int TYPE_PAUSED = 2;
    public final static int TYPE_CANCELED = 3;

    //下载任务的接口
    private DownloadListener downloadListener;
    //用户可以暂停或取消下载任务
    private boolean isPaused = false;
    private boolean isCanceled = false;

    //用户上一次下载后的进度
    private int lastProgress;

    //执行的下载任务
    @Override
    protected Integer doInBackground(String... strings) {
        InputStream inputStream = null;
        //下载的保存目录
        RandomAccessFile savedFile = null;
        File file = null;
        try {
            //记录已下载文件的长度
            long downloadedLength = 0;
            //要下载文件的URL
            String downloadUrl = strings[0];
            //存放目录
            String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
            String directory = Environment.getExternalStorageDirectory().getPath();
            file = new File(directory + "/demo.exe");
            if (file.exists()) {
                downloadedLength = file.length();
            }
            //待下载的文件的总长度
            long contentLength = getContentLength(downloadUrl);
            if (contentLength == 0) {
                return TYPE_FAILED;
            } else if (contentLength == downloadedLength) {
                //已下载字节和文件总字节相等时则下载完成
                return TYPE_SUCCESS;
            }
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    //断点下载,指定从哪个字节开始下载
                    .addHeader("RANGE", "bytes=" + downloadedLength + "-")
                    .url(downloadUrl)
                    .build();
            Response response = client.newCall(request).execute();
            //下载过程
            if (response != null) {
                inputStream = response.body().byteStream();
                //得到具体的存放目录
                savedFile = new RandomAccessFile(file, "rw");
                //跳过已下载的字节
                savedFile.seek(downloadedLength);
                byte[] b = new byte[1024];
                int totalDownload = 0;
                int len;
                while ((len = inputStream.read(b)) != -1) {
                    if (isCanceled) {
                        return TYPE_CANCELED;
                    } else if (isPaused) {
                        return TYPE_PAUSED;
                    } else {
                        //存放下载的数据
                        totalDownload += len;
                        savedFile.write(b,0,len);
                        //计算下载的百分比
                        int progress = (int) ((totalDownload + downloadedLength) * 100 / contentLength);
                        //触发onProgressUpdate方法
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return TYPE_SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭所有的文件流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (savedFile != null) {
                    savedFile.close();
                }
                if (isCanceled && file != null) {
                    file.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return TYPE_FAILED;
    }

    @Override
    protected void onPostExecute(Integer status) {
        super.onPostExecute(status);
        switch (status) {
            case TYPE_SUCCESS:
                downloadListener.onSuccess();
                break;
            case TYPE_FAILED:
                downloadListener.onFailed();
                break;
            case TYPE_PAUSED:
                downloadListener.onPaused();
                break;
            case TYPE_CANCELED:
                downloadListener.onCanceled();
                default:
                break;
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        int progress = values[0];
        if (progress > lastProgress) {
            downloadListener.onProgress(progress);
            lastProgress = progress;
        }
    }

    //获取待下载的文件的总长度
    private long getContentLength(String downloadUrl) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        Response response = client.newCall(request).execute();
        if (response != null && response.isSuccessful()) {
            long contentLength = response.body().contentLength();
            response.close();
            return contentLength;
        }
        return 0;
    }

    //暂停和取消操作
    public void pauseDownload() {
        isPaused = true;
    }

    public void cancelDownload() {
        isCanceled = true;
    }
}
